package zhihuilan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.dto.*;
import zhihuilan.entity.*;
import zhihuilan.mapper.*;
import zhihuilan.params.query.MySearchQueryParam;
import zhihuilan.service.MySearchService;
import zhihuilan.service.MyStaffService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static zhihuilan.common.utils.ToolsUtils.getDistanceSql;

@Service
public class MySearchServiceImpl extends ServiceImpl<MySearchMapper, MySearch> implements MySearchService {


    @Autowired
    private MyCircleMapper myCircleMapper;

    @Autowired
    MyStaffMapper myStaffMapper;

    @Override
    public WxMiniPageDto<MySearchDto> getSearchList(MySearchQueryParam mySearchQueryParam,List<Integer> strings) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id",  strings);
        System.out.println(strings);
        Page<MyStaffShopGoods> page = myStaffShopGoodsMapper.selectPage( new Page<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize()), queryWrapper);
        WxMiniPageDto<MySearchDto> pageDto =  new WxMiniPageDto<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize());
        pageDto.setData(page.getRecords().stream().map(po->{
            MySearchDto mySearchDto = new MySearchDto();
            if(po.getShopid()==0){
              MyStaff    staff=  myStaffMapper.selectById(po.getStaffId());
                mySearchDto.setStaffTitle(staff.getTitle());
                mySearchDto.setStaffHeadimgurl(staff.getHeadimgurl());
                mySearchDto.setStaffLogo(staff.getLogo());
            }
                mySearchDto.setPid(po.getId());
                mySearchDto.setName(po.getName());
                mySearchDto.setContent(po.getContent());
                mySearchDto.setLogo(po.getImage().split(",")[0]);
                mySearchDto.setId(po.getId());
                mySearchDto.setFid(po.getShopid());
                mySearchDto.setDistance(po.getDistance());
                mySearchDto.setStaffId(po.getStaffId());

            return mySearchDto;
        }).collect(Collectors.toList()));
        return pageDto;
    }

//    @Override
//    public WxMiniPageDto<MySearchDto> getSearchList(MySearchQueryParam mySearchQueryParam, List keywordList) {
//        if(mySearchQueryParam.getType().equals(1)){
//            StringBuilder orConditions = new StringBuilder();
//            String last = "order by ";
//            if (mySearchQueryParam.getKeyword() != null && !mySearchQueryParam.getKeyword().isEmpty()) {
//                orConditions.append("LOWER(a.remark)  like '%").append(mySearchQueryParam.getKeyword().toLowerCase()).append("%'");
//                orConditions.append(" or  a.name like '%").append(mySearchQueryParam.getKeyword()).append("%'");
//                last += "  CASE WHEN LOWER(a.remark ) like  '%" + mySearchQueryParam.getKeyword().toLowerCase() + "%' THEN 1  WHEN a.name like '%" + mySearchQueryParam.getKeyword() + "%' THEN 2";
//                for (int i = 0; i < keywordList.size(); i++) {
//                    Map map = (Map) keywordList.get(i);
//                    last += " WHEN LOWER(a.remark) like '%" + map.get("word").toString().toLowerCase() + "%' THEN " + (i + i + 3);
//                    last += " WHEN a.name like '%" + map.get("word").toString().toLowerCase() + "%' THEN " + (i + i + 4);
//                    String s = map.get("word").toString();
//                    orConditions.append(" or  LOWER(a.remark )  like '%").append(s.toLowerCase()).append("%'");
//                    orConditions.append(" or  a.name like '%").append(s).append("%'");
//                }
//                last += " END,";
//            }
//            last += " a.create_time desc ";
//            List<MyStaffShopGoodsDto> goods = myStaffShopGoodsMapper.selectMyStaffShopGoodsNoLatPage((mySearchQueryParam.getPage()-1)*mySearchQueryParam.getPageSize(), mySearchQueryParam.getPageSize(),mySearchQueryParam.getDistrictid(),last,orConditions.toString());
//            Integer goodsTotal = myStaffShopGoodsMapper.selectMyStaffShopGoodsNoLatTotal(mySearchQueryParam.getDistrictid(),orConditions.toString());
//            WxMiniPageDto<MySearchDto> resultPage = new WxMiniPageDto<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize());// 第1页，每页10条数据
//            List<MySearchDto> convertList = goods.stream().map(po -> {
//                MySearchDto mySearchDto = new MySearchDto();
//                mySearchDto.setPid(po.getId());
//                mySearchDto.setName(po.getName());
//                mySearchDto.setContent(po.getContent());
//                mySearchDto.setLogo(po.getImage().split(",")[0]);
//                mySearchDto.setId(po.getId());
//                mySearchDto.setFid(po.getShopid());
//                mySearchDto.setDistance(po.getDistance());
//                mySearchDto.setStaffId(po.getStaffId());
//                mySearchDto.setStaffTitle(po.getStaffTitle());
//                mySearchDto.setStaffHeadimgurl(po.getStaffHeadimgurl());
//                mySearchDto.setStaffLogo(po.getStaffLogo());
//                return mySearchDto;
//            }).collect(Collectors.toList());
//            resultPage.setData(convertList);
//            resultPage.setTotal(goodsTotal);
//            return resultPage;
//        }else {
//            StringBuilder orConditions = new StringBuilder();
//            String last = "";
//            if (mySearchQueryParam.getKeyword() != null && !mySearchQueryParam.getKeyword().isEmpty()) {
//                orConditions.append("LOWER(a.content)  like '%").append(mySearchQueryParam.getKeyword().toLowerCase()).append("%'");
//                orConditions.append(" or a.title like '%").append(mySearchQueryParam.getKeyword()).append("%'");
//                orConditions.append(" or b.title like '%").append(mySearchQueryParam.getKeyword()).append("%'");
//                last += "  CASE WHEN LOWER(a.content ) like  '%" + mySearchQueryParam.getKeyword().toLowerCase() + "%' THEN 1  WHEN a.title like '%" + mySearchQueryParam.getKeyword() + "%' THEN 2  WHEN b.title like '%" + mySearchQueryParam.getKeyword() + "%' THEN 3";
//                for (int i = 0; i < keywordList.size(); i++) {
//                    Map map = (Map) keywordList.get(i);
//                    last += " WHEN LOWER(a.content ) like '%" +  map.get("word").toString().toLowerCase() + "%' THEN " + (i + i + 4);
//                    last += " WHEN a.title like '%" +  map.get("word").toString().toLowerCase()+ "%' THEN " + (i + i + 5);
//                    last += " WHEN b.title like '%" +  map.get("word").toString().toLowerCase() + "%' THEN " + (i + i + 6);
//                    String s = map.get("word").toString();
//                    orConditions.append(" or  LOWER(a.content )  like '%").append(s.toLowerCase()).append("%'");
//                    orConditions.append(" or  a.title like '%").append(s).append("%'");
//                    orConditions.append(" or  b.title like '%").append(s).append("%'");
//                }
//                last += " END ";
//            }
//            List<MySearchDto> list = myCircleMapper.selectMyCirclePage((mySearchQueryParam.getPage()-1)*mySearchQueryParam.getPageSize(),mySearchQueryParam.getPageSize(),mySearchQueryParam.getDistrictid(),orConditions.toString(),last);
//            Integer goodsTotal = myCircleMapper.selectMyCircleTotal(mySearchQueryParam.getDistrictid(),orConditions.toString());
//            WxMiniPageDto<MySearchDto> resultPage = new WxMiniPageDto<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize());// 第1页，每页10条数据
//            resultPage.setData(list);
//            resultPage.setTotal(goodsTotal);
//            return resultPage;
//        }
//
//      //  Page<MySearch> page = baseMapper.selectPage( new Page<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize()), queryWrapper) ;
//      //  return page;
//    }


    @Override
    public Map getSearchIndexList(MySearchQueryParam mySearchQueryParam, List keywordList) {
        QueryWrapper<MySearch> queryWrapper = Wrappers.query();
        QueryWrapper<MySearch> queryWrapper1 = Wrappers.query();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("type", 0);
        if (mySearchQueryParam.getDistrictid() != null && 100000 < mySearchQueryParam.getDistrictid()) {
            queryWrapper.eq("districtid", mySearchQueryParam.getDistrictid());
            queryWrapper1.eq("districtid", mySearchQueryParam.getDistrictid());
        } else if (mySearchQueryParam.getDistrictid() != null && 100000 > mySearchQueryParam.getDistrictid() && mySearchQueryParam.getDistrictid() > 1000) {
            queryWrapper.eq("districtid1", mySearchQueryParam.getDistrictid());
            queryWrapper1.eq("districtid", mySearchQueryParam.getDistrictid());
        } else if (mySearchQueryParam.getDistrictid() != null && mySearchQueryParam.getDistrictid() > 0) {
            queryWrapper.eq("districtid2", mySearchQueryParam.getDistrictid());
            queryWrapper1.eq("districtid", mySearchQueryParam.getDistrictid());
        }
        if (mySearchQueryParam.getKeyword() != null && !mySearchQueryParam.getKeyword().isEmpty()) {
            StringBuilder orConditions = new StringBuilder();
            orConditions.append("LOWER(CONVERT(content USING utf8))  like '%").append(mySearchQueryParam.getKeyword().toLowerCase()).append("%'");
            orConditions.append(" or  name like '%").append(mySearchQueryParam.getKeyword()).append("%'");
            String last = " order by CASE WHEN LOWER(CONVERT(content USING utf8)) like  '%" + mySearchQueryParam.getKeyword().toLowerCase() + "%' THEN 1  WHEN name like '%" + mySearchQueryParam.getKeyword() + "%' THEN 2";
            for (int i = 0; i < keywordList.size(); i++) {
                Map map = (Map) keywordList.get(i);
                String s = map.get("word").toString();
                last += " WHEN LOWER(CONVERT(content USING utf8)) like '%" +s.toLowerCase() + "%' THEN " + (i + i + 3);
                last += " WHEN name like '%" +s.toLowerCase() + "%' THEN " + (i + i + 4);
                orConditions.append(" or  LOWER(CONVERT(content USING utf8))  like '%").append(s.toLowerCase()).append("%'");
                orConditions.append(" or  name like '%").append(s).append("%'");
            }
            queryWrapper.and(wp -> wp.apply(orConditions.toString()));
            queryWrapper1.and(wp -> wp.apply(orConditions.toString()));
            last += " ELSE " + (keywordList.size() + 5) + " END,create_time desc ";
            queryWrapper1.last(last);
            queryWrapper.last(last);
        }
        PageDto<MySearch> page = new PageDto<>(mySearchQueryParam.getPage(), mySearchQueryParam.getShopSize());
        PageDto<MySearch> shoplist = baseMapper.selectPage(page, queryWrapper);
        queryWrapper1.eq("type", 1);
        queryWrapper1.eq("fid", 0);
        queryWrapper1.eq("status", 1);
        PageDto<MySearch> page1 = new PageDto<>(mySearchQueryParam.getPage(), mySearchQueryParam.getGoodsSize());
        PageDto<MySearch> goodsList = baseMapper.selectPage(page1, queryWrapper1);
        Map map = new HashMap();
        map.put("goodsList", goodsList);
        map.put("shoplist", shoplist);
        return map;
    }


    @Override
    public WxMiniPageDto<MySearchDto> getSearchShopList(MySearchQueryParam mySearchQueryParam, List keywordList) {
        QueryWrapper<MyStaffShop> queryWrapper = Wrappers.query();
        queryWrapper.eq("status", 1);
        queryWrapper.select("*", ToolsUtils.getDistanceSqlTencent(mySearchQueryParam.getLat(), mySearchQueryParam.getLng()) + "*1000 as distance");
        queryWrapper.le(ToolsUtils.getDistanceSqlTencent(mySearchQueryParam.getLat(), mySearchQueryParam.getLng()), 500);
        StringBuilder orConditions = new StringBuilder();
        String sql="";
        if (mySearchQueryParam.getKeyword() != null && !mySearchQueryParam.getKeyword().isEmpty()) {
            orConditions.append("LOWER(intro)  like '%").append(mySearchQueryParam.getKeyword().toLowerCase()).append("%'");
            orConditions.append(" or  title like '%").append(mySearchQueryParam.getKeyword()).append("%'");
            queryWrapper.orderByAsc("distance");
            for (int i = 0; i < keywordList.size(); i++) {
                Map map = (Map) keywordList.get(i);
                String s = map.get("word").toString();
                sql+= " or  a.name like '%"+s+"%' ";
                sql+= " or  LOWER(a.remark) like '%"+s.toLowerCase()+"%' ";
                orConditions.append(" or  LOWER(intro)  like '%").append(s.toLowerCase()).append("%'");
                orConditions.append(" or  title like '%").append(s).append("%'");
            }
            queryWrapper.and(wp -> wp.apply(orConditions.toString()));

        }
        if(mySearchQueryParam.getType()==2){
            Page<MyStaffShop> page = myStaffShopMapper.selectPage( new Page<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize()), queryWrapper);
            List<MySearchDto> convertList = page.getRecords().stream().map(po -> {
                MySearchDto mySearchDto = new MySearchDto();
                mySearchDto.setPid(po.getId());
                mySearchDto.setFid(0);
                mySearchDto.setName(po.getTitle());
                mySearchDto.setContent(po.getIntro());
                mySearchDto.setLogo(po.getLogo());
                mySearchDto.setId(po.getId());
                mySearchDto.setDistance(po.getDistance());
                return mySearchDto;
            }).collect(Collectors.toList());

            WxMiniPageDto<MySearchDto> resultPage = new WxMiniPageDto<>(page.getCurrent(), page.getSize());// 第1页，每页10条数据
              BeanUtils.copyProperties(page, resultPage);
            resultPage.setData(convertList);
            return resultPage;
        }else {
            List<MyStaffShopGoods> goods = myStaffShopGoodsMapper.selectMyStaffShopGoodsPage((mySearchQueryParam.getPage()-1)*mySearchQueryParam.getPageSize(), mySearchQueryParam.getPageSize(),Double.parseDouble(mySearchQueryParam.getLat()),Double.parseDouble(mySearchQueryParam.getLng()),mySearchQueryParam.getKeyword(),sql);
            Integer goodsTotal = myStaffShopGoodsMapper.selectMyStaffShopGoodsTotal(Double.parseDouble(mySearchQueryParam.getLat()),Double.parseDouble(mySearchQueryParam.getLng()),mySearchQueryParam.getKeyword(),sql);
            WxMiniPageDto<MySearchDto> resultPage = new WxMiniPageDto<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize());// 第1页，每页10条数据
            List<MySearchDto> convertList = goods.stream().map(po -> {
                MySearchDto mySearchDto = new MySearchDto();
                mySearchDto.setPid(po.getId());
                mySearchDto.setName(po.getName());
                mySearchDto.setContent(po.getContent());
                mySearchDto.setLogo(po.getImage().split(",")[0]);
                mySearchDto.setId(po.getId());
                mySearchDto.setFid(po.getShopid());
                mySearchDto.setDistance(po.getDistance());
                return mySearchDto;
            }).collect(Collectors.toList());
            resultPage.setData(convertList);
            resultPage.setTotal(goodsTotal);
            return resultPage;
        }


    }

    @Autowired
    private MyStaffShopMapper myStaffShopMapper;

    @Autowired
    private MyStaffShopGoodsMapper myStaffShopGoodsMapper;

    @Override
    public Map getSearchShopGoodsList(MySearchQueryParam mySearchQueryParam, List keywordList) {
        QueryWrapper<MyStaffShop> queryWrapper = Wrappers.query();
        queryWrapper.select("*,latgd,lnggd",  ToolsUtils.getDistanceSqlTencent(mySearchQueryParam.getLat(), mySearchQueryParam.getLng()) + "*1000 as distance");
        queryWrapper.le( ToolsUtils.getDistanceSqlTencent(mySearchQueryParam.getLat(), mySearchQueryParam.getLng()), 500);
        String sql = "";

        if (mySearchQueryParam.getKeyword() != null && !mySearchQueryParam.getKeyword().isEmpty()) {
            StringBuilder orConditions = new StringBuilder();
            orConditions.append("LOWER(intro)  like '%").append(mySearchQueryParam.getKeyword().toLowerCase()).append("%'");
            orConditions.append(" or  title like '%").append(mySearchQueryParam.getKeyword()).append("%'");
            queryWrapper.orderByAsc("distance");
         //   String last = " order by distance asc,CASE WHEN LOWER(content) like  '%" + mySearchQueryParam.getKeyword().toLowerCase() + "%' THEN 1  WHEN name like '%" + mySearchQueryParam.getKeyword() + "%' THEN 2";


            for (int i = 0; i < keywordList.size(); i++) {
                Map map = (Map) keywordList.get(i);
                String s = map.get("word").toString();
                sql+= " or  a.name like '%"+s+"%' ";
                sql+= " or  LOWER(a.remark) like '%"+s.toLowerCase()+"%' ";
                orConditions.append(" or  LOWER(intro)  like '%").append(s.toLowerCase()).append("%'");
                orConditions.append(" or  title like '%").append(s).append("%'");
            }
            queryWrapper.and(wp -> wp.apply(orConditions.toString()));

        }

        Page<MyStaffShop> shopList = myStaffShopMapper.selectPage(new Page<>(mySearchQueryParam.getPage(), mySearchQueryParam.getPageSize()), queryWrapper);

        List<MyStaffShopGoods> goods = myStaffShopGoodsMapper.selectMyStaffShopGoodsPage((mySearchQueryParam.getPage()-1)*mySearchQueryParam.getPageSize(), mySearchQueryParam.getPageSize(),Double.parseDouble(mySearchQueryParam.getLat()),Double.parseDouble(mySearchQueryParam.getLng()),mySearchQueryParam.getKeyword(),sql);
        Integer goodsTotal = myStaffShopGoodsMapper.selectMyStaffShopGoodsTotal(Double.parseDouble(mySearchQueryParam.getLat()),Double.parseDouble(mySearchQueryParam.getLng()),mySearchQueryParam.getKeyword(),sql);
        if(goods.size()>0){
                goods.stream().forEach(paGoods->{
                paGoods.setLogo(paGoods.getImage().split(",")[0]);
                paGoods.setPid(paGoods.getId());
                paGoods.setFid(paGoods.getShopid());
            });
        }
        shopList.getRecords().stream().forEach(po -> {
                po.setName(po.getTitle());
                po.setContent(po.getIntro());
                po.setType(2);
                po.setPid(po.getId());
                po.setFid(po.getId());
        });
        Map map = new HashMap();
        map.put("goodsData", goods);
        map.put("goodsTotal",goodsTotal);
        map.put("shopTotal", shopList.getTotal());
        map.put("shopData", shopList.getRecords());
        return map;
    }

    @Override
    public MySearch addEntity(MySearch entity) {
        this.baseMapper.insert(entity);
        if (!ObjectUtils.isEmpty(entity)) {
            return entity;
        } else {
            return null;
        }
    }

    @Override
    public MySearch updateEntity(MySearch entity) {
        QueryWrapper<MySearch> queryWrapper = Wrappers.query();
        queryWrapper.eq("tb_name", entity.getTbName());
        queryWrapper.eq("pid", entity.getPid());
        this.baseMapper.update(entity, queryWrapper);
        if (!ObjectUtils.isEmpty(entity)) {
            return entity;
        } else {
            return null;
        }
    }

    @Override
    public Boolean deleteByTableAndId(String tableName, Integer pid) {
        QueryWrapper<MySearch> queryWrapper = Wrappers.query();
        queryWrapper.eq("tb_name", tableName);
        queryWrapper.eq("pid", pid);
        int count = this.baseMapper.delete(queryWrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }

    }
    @Override
    public Boolean deleteByTableAndFid(String tableName, Integer pid, Integer fid, Integer staffId) {
        if (ObjectUtils.isEmpty(tableName)) {
            return false;
        } else {
            if (ObjectUtils.isEmpty(pid) || ObjectUtils.isEmpty(fid) || ObjectUtils.isEmpty(staffId)) {
                return false;
            }
        }
        QueryWrapper<MySearch> queryWrapper = Wrappers.query();
        if (!ObjectUtils.isEmpty(tableName))
            queryWrapper.eq("tb_name", tableName);
        if (!ObjectUtils.isEmpty(pid))
            queryWrapper.eq("pid", pid);
        if (!ObjectUtils.isEmpty(fid))
            queryWrapper.eq("fid", fid);
        if (!ObjectUtils.isEmpty(staffId))
            queryWrapper.eq("staff_id", staffId);
        int count = this.baseMapper.delete(queryWrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public MySearch updateEntityToTable(MySearch entity) {
        QueryWrapper<MySearch> queryWrapper = Wrappers.query();
        if (!ObjectUtils.isEmpty(entity.getTbName()))
            queryWrapper.eq("tb_name", entity.getTbName());
        if (!ObjectUtils.isEmpty(entity.getPid()))
            queryWrapper.eq("pid", entity.getPid());
        if (!ObjectUtils.isEmpty(entity.getFid()))
            queryWrapper.eq("fid", entity.getFid());
        if (!ObjectUtils.isEmpty(entity.getStaffId()))
            queryWrapper.eq("staff_id", entity.getStaffId());
        this.baseMapper.update(entity, queryWrapper);
        if (!ObjectUtils.isEmpty(entity)) {
            return entity;
        } else {
            return null;
        }
    }
}
